from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
import json
from asgiref.sync import async_to_sync
from datetime import datetime
from chat.models import *
from django.contrib.sessions.models import Session


class ChatConsumer(WebsocketConsumer):
    def websocket_connect(self, message):
        print("有人链接了")
        self.group_id = self.scope['url_route']['kwargs']['gid']
        self.uid = self.scope['url_route']['kwargs']['uid']
        self.gid_count = 0


        # Websocket
        async_to_sync(self.channel_layer.group_add)(self.group_id, self.channel_name)
        # 接受客户连接
        self.accept()

    def websocket_receive(self, message):
        # Send message to room group
        print("websocket_receive-----message------------------------------>")
        print(message)
        if message['text'] == 'count':
            # 实时更新群聊人数
            print('查询人数')
            self.gid_count = Websocket.objects.filter(gid=self.group_id).first().member_count
            async_to_sync(self.channel_layer.group_send)(self.group_id, {'type': 'online_user', 'message': {'gid_count': self.gid_count, 'gid': self.group_id, 'status': 'count'}})
        elif message['text'] == 'close':
            print('更新人数')
            self.gid_count = Websocket.objects.filter(gid=self.group_id).first().member_count - 1  # 直接减1，前端ajax请求慢，使用先手动处理
            print('人数：', self.gid_count)
            async_to_sync(self.channel_layer.group_send)(self.group_id, {'type': 'online_user', 'message': {'gid_count': self.gid_count, 'gid': self.group_id, 'type': 'update'}})
            self.close()
        else:
            message['uid'] = str(self.uid)
            message['gid'] = str(self.group_id)
            async_to_sync(self.channel_layer.group_send)(self.group_id, {'type': 'chat_message', 'message': message})

    def websocket_disconnect(self, message):
        # 客户端主动断开连接时，触发
        print("断开连接")
        async_to_sync(self.channel_layer.group_discard)(self.group_id, self.channel_name)
        raise StopConsumer()

    def chat_message(self, event):
        message = event['message']
        time = str(datetime.now().time())
        message['time'] = time
        self.send(text_data=json.dumps({"message": message}))
    
    def online_user(self, event):  
        self.send(text_data=json.dumps({"count_message": event['message']}))

